<template>
    <el-table 
      :data="processedTableData" 
      style="width: 100%" 
      border
      :span-method="handleSpanMethod"
    >
      <!-- 主表信息列 -->
      <el-table-column prop="purret_code" label="退货单号" width="180" />
      <el-table-column prop="po_name" label="采购单名称" width="180" />
      <el-table-column prop="vendor_name" label="供应商" width="150" />
      <el-table-column prop="purret_returncause" label="退货原因" width="200" />
      <el-table-column prop="purret_returntime" label="退货时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.purret_returntime) }}
        </template>
      </el-table-column>
      
      <!-- 商品详情列 -->
      <el-table-column prop="pro_name" label="商品名称" width="150" />
      <el-table-column prop="pro_code" label="商品编码" width="150" />
      <el-table-column prop="pro_brand" label="品牌" width="120" />
      <el-table-column prop="pro_model" label="型号" width="120" />
      <el-table-column prop="po_number" label="采购数量" width="100" align="right" />
      <el-table-column prop="podet_inbound_quantity" label="已入库数量" width="100" align="right" />
      <el-table-column prop="number_returns" label="退货数量" width="100" align="right" />
      
      <!-- 状态列 -->
    </el-table>

    <!-- <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      @current-change="fetchData"
      layout="prev, pager, next"
    /> -->
    <div class="pagination-wrapper">
            <el-pagination 
                v-model:current-page="currentPage" 
                v-model:page-size="pageSize" 
                :page-sizes="[5, 10, 20, 50]"
                :background="true" 
                layout="total, sizes, prev, pager, next, jumper" 
                :total="pageCount"
                @size-change="handleSizeChange" 
                @current-change="handleCurrentChange" 
            />
        </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  code: {
    type: String,
    required: true
  }
})

// 原始数据和分页
const rawData = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const loading = ref(false)
const pageCount = ref(0)

// 处理后的表格数据（展开details）
const processedTableData = computed(() => {
  const result = []
  rawData.value.forEach(item => {
    if (item.details && item.details.length > 0) {
      item.details.forEach((detail, index) => {
        result.push({
          ...item,
          ...detail,
          // 标记这是第几个detail，用于合并单元格
          _detailIndex: index,
          _detailCount: item.details.length
        })
      })
    } else {
      result.push({
        ...item,
        _detailIndex: 0,
        _detailCount: 1
      })
    }
  })
  return result
})

// 合并单元格方法
const handleSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 需要合并的列（主表信息）
  const mergeColumns = [
    'purret_code', 
    'po_name', 
    'vendor_name',
    'purret_returncause',
    'purret_returntime',
    'pu_state'
  ]
  
  if (mergeColumns.includes(column.property)) {
    if (row._detailIndex === 0) {
      return {
        rowspan: row._detailCount,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}
function handleSizeChange(){

}
function handleCurrentChange(){

}
function count(){
  axios.get('http://localhost:5181/api/Pu/GetPuWhereCount',{
    params:{
      Purret_code:props.code,
    },
    headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
                }
  }).then((result) => {
    pageCount.value = result.data;
  }).catch((err) => {
    console.error('总条数加载失败', err);
  });
}


// 时间格式化
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:5181/api/Pu/GetPuFyWhereSelect', {
      params: {
        Purret_code: props.code,
        currentPage: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    rawData.value = response.data || []
    total.value = response.data?.length || 0
  } catch (error) {
    ElMessage.error('获取退货记录失败: ' + error.message)
    console.error('API 错误:', error)
  } finally {
    loading.value = false
  }
}

// 监听 code 变化
watch(() => props.code, (newCode) => {
  if (newCode) {
    currentPage.value = 1
    fetchData()
    count()
  }
}, { immediate: true })
</script>

<style scoped>

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
.pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>